package service

import (
	"encoding/json"
	"errors"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/models"
	"rock/customer/modules/redisModules"
	"rock/customer/public"
	"time"
)

type Robot struct {
}

// 机器人
func (r *Robot) Robot(gc *gin.Context, tx *gorm.DB) (data dto.Robot, err error) {
	// 取缓存
	redisCache := redisModules.ClientRedis.Get(initParam.RobotPrefix)
	val, err := redisCache.Result()
	if err == nil {
		err = json.Unmarshal([]byte(val), &data)
		if err != nil {
			return
		}
		return
	} else {
		if err != redis.Nil {
			return
		}
	}
	// 查db
	err = tx.SetCtx(public.GetGinTraceContext(gc)).Model(&models.WkbImRobot{}).Where("deleted = 2").Scan(&data).Error
	if err != nil {
		if err.Error() != gorm.ErrRecordNotFound.Error() {
			err = errors.New(initParam.DataIsNotExist)
			return
		}
	}
	if data.Id == 0 {
		err = errors.New(initParam.DataIsNotExist)
		return
	}
	// 存缓存
	err = addRedis(data, initParam.RobotPrefix, 15*24*time.Hour)
	return
}

// 机器人 - 新建
func (r *Robot) CreateRobot(gc *gin.Context, tx *gorm.DB, robot *models.WkbImRobot) error {
	return tx.SetCtx(public.GetGinTraceContext(gc)).Model(&models.WkbImRobot{}).Create(robot).Error
}